<!-- 表格demo -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue Element UI Table Example</title>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <style>
    .edit-text {
      color: orange;
      cursor: pointer;
    }
    .mt50 {
      margin-top: 50px
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="mt50">
      <el-button type="primary" @click="editHeader">编辑头部信息</el-button>
      <el-dialog :title="'编辑头部信息'" :visible.sync="dialogVisible3" width="600px">
        <el-form :model="editedItem">
          <el-form-item label="用户余额">
            <el-input v-model="editedItem3.userBalanceVal"></el-input>
          </el-form-item>
          <el-form-item label="剩余余额">
            <el-input v-model="editedItem3.remainingBalanceVal"></el-input>
          </el-form-item>
          <el-form-item label="网站点击量">
            <el-input v-model="editedItem3.webClickCountVal"></el-input>
          </el-form-item>
          <el-form-item label="点击费用">
            <el-input v-model="editedItem3.clickCostVal"></el-input>
          </el-form-item>
          <el-form-item label="点击次数">
            <el-input v-model="editedItem3.clickCountVal"></el-input>
          </el-form-item>
          <el-form-item label="成交均价">
            <el-input v-model="editedItem3.averageTransactionPrice"></el-input>
          </el-form-item>
          <el-form-item label="今日销售额">
            <el-input v-model="editedItem3.todayTotalSales"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible3 = false">取消</el-button>
          <el-button type="primary" @click="saveEdit3">保存</el-button>
        </span>
      </el-dialog>
    </div>


    <div class="mt50">
      <el-button type="primary" @click="addRow2">添加</el-button>
      <el-table :data="tableData2">
        <el-table-column prop="region" label="地区"></el-table-column> 
        <el-table-column prop="score" label="访问量" sortable></el-table-column>
        <el-table-column label="编辑">
          <template slot-scope="{ row,$index }">
            <span class="edit-text" @click="editRow2(row,$index)">修改</span>
            <span class="edit-text ml10" @click="deleteRow2(row,$index)">删除</span>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :title="methodType2=='edit'?'编辑地区':'添加地区'" :visible.sync="dialogVisible2" width="600px">
        <el-form :model="editedItem2" label-width="80px">
          <el-form-item label="地区">
            <el-input v-model="editedItem2.region" controls-position="right"></el-input>
          </el-form-item>
          <el-form-item label="访问量">
            <el-input-number v-model="editedItem2.score" controls-position="right"></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="saveEdit2">保存</el-button>
        </span>
      </el-dialog>
    </div>

    <el-button type="primary" @click="addRow">添加</el-button>
    <el-table :data="tableData">
        <el-table-column prop="category" label="消费类别"></el-table-column>
        <el-table-column prop="amount" label="消费金额" sortable></el-table-column>
        <el-table-column prop="time" label="时间" sortable></el-table-column>
        <el-table-column prop="quantity" label="数量" sortable></el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式"></el-table-column>
        <el-table-column prop="account" label="存款账户"></el-table-column>
        <el-table-column label="编辑">
          <template slot-scope="{ row,$index }">
            <span class="edit-text" @click="editRow(row,$index)">修改</span>
            <span class="edit-text" @click="deleteRow(row,$index)">删除</span>
          </template>
        </el-table-column>
      </el-table>


    <el-dialog :title="methodType=='edit'?'编辑消费记录':'添加消费记录'" :visible.sync="dialogVisible">
      <el-form :model="editedItem">
        <el-form-item label="消费类别">
          <el-input v-model="editedItem.category"></el-input>
        </el-form-item>
        <el-form-item label="消费金额">
          <el-input-number v-model="editedItem.amount" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="editedItem.time" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="editedItem.quantity" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="支付方式">
            <el-input v-model="editedItem.paymentMethod"></el-input>
        </el-form-item>
        <el-form-item label="存款账户">
            <el-input v-model="editedItem.account"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </span>
    </el-dialog>



  </div>

  <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
  <script src="https://unpkg.com/element-ui@2.15.6/lib/index.js"></script>
  <script>

new Vue({
      el: '#app',
      data() {
        return {
          tableData: [],
          dialogVisible: false,
          editedItem: {},
          methodType: null,
          editedIndex: null,

          tableData2: [],
          dialogVisible2: false,
          editedItem2: {},
          methodType2: null,
          editedIndex2: null,

          topData: {},
          editedItem3: {},
          dialogVisible3: false,
        };
      },
      created() {
        this.fetchData();
        this.fetchData2();
        this.getTopData();
      },
      methods: {
        async fetchData() {
          try {
            let response = await fetch('/list4.json');
            let data = await response.json();
            this.tableData = data;
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        },
        // ... 其他方法 ...
        addRow() {
          // 添加行逻辑
          this.methodType = "add";
          this.editedItem = {
            category:'',
            amount:'',
            time:'',
            quantity:'',
            paymentMethod:'',  
            account:''        
          };
          this.dialogVisible = true;
        },

        editRow(row,index) {
          this.methodType = "edit";
          this.editedItem = Object.assign({}, row);
          this.editedIndex = index;
          this.dialogVisible = true;
        },
        deleteRow(row,$index) {
          // 删除行逻辑
          this.$confirm('确认删除吗？', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.tableData.splice($index, 1);
            this.setTableData(JSON.parse(JSON.stringify(this.tableData)),'list4')
            // this.fetchData2()  删除后重新拉取数据，看是否需要
          })
          .catch(() => {});
          // let index = this.tableData.findIndex(item => item === row);
          //   if (index > -1) {
          //       this.tableData.splice(index, 1);
          //   }
          
        },
        saveEdit() {
          if(this.methodType == "add"){
            this.tableData.push(this.editedItem)
          }else if(this.methodType == "edit"){
            this.tableData[this.editedIndex] = this.editedItem;
          }
          this.setTableData(JSON.parse(JSON.stringify(this.tableData)),'list4')
           // this.fetchData()  新增或修改后重新拉取数据，看是否需要
          
          // let index = this.tableData.findIndex(item => item === this.editedItem);
          // if (index > -1) {
          //   this.tableData.splice(index, 1, this.editedItem);
          // }
          // this.dialogVisible = false;
        },
        setTableData(tableData,file) {
          let _this = this;
          fetch("/saveData",{
            method: "POST",
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              file: file,
              data: JSON.stringify(tableData)
            })
          }).then(function(res){
            return res.json()
          }).then(function(data){
            console.log(data)
            _this.$message({ message:"操作成功", type:"success" })
            _this.tableData = tableData
            _this.dialogVisible = false;
          }).catch(function(e){
            console.error(e)
            _this.$message({ message:"操作失败", type:"error" })
          })
        },

        async fetchData2() {
          try {
            let response = await fetch('/data.json');
            let data = await response.json();
            this.tableData2 = data;
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        },
        // ... 其他方法 ...
        addRow2() {
          // 添加行逻辑
          this.methodType2 = "add";
          this.editedItem2 = {
            region:'',
            score:''
          };
          this.dialogVisible2 = true;
        },

        editRow2(row,index) {
          this.methodType2 = "edit";
          this.editedItem2 = Object.assign({}, row);
          this.editedIndex2 = index;
          this.dialogVisible2 = true;
        },
        deleteRow2(row,$index) {
          // 删除行逻辑
          this.$confirm('确认删除吗？', '提示', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            this.tableData2.splice($index, 1);
            this.setTableData2(JSON.parse(JSON.stringify(this.tableData2)),'data')
           // this.fetchData2()  删除后重新拉取数据，看是否需要
          })
          .catch(() => {});
        },
        saveEdit2() {
          if(this.methodType2 == "add"){
            this.tableData2.push(this.editedItem2)
          }else if(this.methodType2 == "edit"){
            this.tableData2[this.editedIndex2] = this.editedItem2;
          }
          this.setTableData2(JSON.parse(JSON.stringify(this.tableData2)),'data')
           // this.fetchData2()  新增或修改后重新拉取数据，看是否需要
        },
        setTableData2(tableData,file) {
          let _this = this;
          fetch("/saveData",{
            method: "POST",
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              file: file,
              data: JSON.stringify(tableData)
            })
          }).then(function(res){
            return res.json()
          }).then(function(data){
            console.log(data)
            _this.$message({ message:"操作成功", type:"success" })
            _this.tableData2 = tableData
            _this.dialogVisible2 = false;
          }).catch(function(e){
            console.error(e)
            _this.$message({ message:"操作失败", type:"error" })
          })
        },

        getTopData() {
          let _this=this;
          fetch("top.json").then(function(res){
            return res.json()
          }).then(function(data){
            _this.$set(_this,'topData',data);
          }).catch(function(e){
            console.error(e)
          })
        },
        editHeader() {
          this.editedItem3 = JSON.parse(JSON.stringify(this.topData));
          this.dialogVisible3 = true;
        },
        saveEdit3() {
          let topData = JSON.parse(JSON.stringify(this.editedItem3));
          this.setTopData(topData,'top')
        },
        setTopData(topData,file) {
          let _this = this;
          fetch("/saveData",{
            method: "POST",
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              file: file,
              data: JSON.stringify(topData)
            })
          }).then(function(res){
            return res.json()
          }).then(function(data){
            console.log(data)
            _this.$message({ message:"操作成功", type:"success" })
            _this.topData = topData
            _this.dialogVisible3 = false;
          }).catch(function(e){
            console.error(e)
            _this.$message({ message:"操作失败", type:"error" })
          })
        },
      }
    });

  </script>
</body>
</html>
